package com.asimplefox.controllers;

import com.asimplefox.entity.Types;
import com.asimplefox.service.ITypesService;
import com.asimplefox.service.abst.ResultU;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.stream.Collectors;

/**
 * @author github kloping
 * @date 2024/11/24-11:09
 */
@RestController
@RequestMapping("/api/types")
@Slf4j
public class TypesController implements ResultU {

    @Autowired
    ITypesService typesService;

    @GetMapping
    public Object types() {
        return typesService.lambdaQuery().select(Types::getName).list().stream().map(Types::getName).collect(Collectors.toSet());
    }

    @GetMapping("/del")
    @PreAuthorize("hasAnyAuthority('admin','system')")
    public Object del(@RequestParam("name") String name) {
        if (typesService.lambdaUpdate().eq(Types::getName, name).remove()) {
            return success("ok");
        } else return fail("fail");
    }

    @PreAuthorize("hasAnyAuthority('admin','system')")
    @PutMapping
    public Object put(@RequestParam("name") String name, @RequestParam("vlid") Integer vlid) {
        Types types = new Types();
        types.setName(name);
        types.setVlid(vlid);
        if (typesService.lambdaQuery().eq(Types::getName, name).eq(Types::getVlid, vlid).one() != null) {
            return fail("exist");
        }
        if (typesService.save(types)) {
            return success("ok");
        } else return fail("fail");
    }
}
